//
//  TravelImpressionController.m
//  WildDonkey
//
//  Created by 佟小波 on 15/3/28.
//  Copyright (c) 2015年 lanou. All rights reserved.
//

#import "TravelImpressionController.h"
#import "ViewpointTableViewCell.h"
#import "SubViewpointTVCell.h"
#import "SurroundingFoodTVController.h"
#import "SurroundHouseTVController.h"
#import "SurroundingTrafficTVController.h"
#import "SurroundingViewTVController.h"
#import "PhotoTVController.h"
#import "AFNetworking.h"
#import "ViewPoint.h"
#import "GPSViewController.h"
#import "MJRefresh.h"

@interface TravelImpressionController ()

@property (nonatomic,retain) NSString *noteString;
@property (nonatomic,retain) UIImageView *headerImage;
@property (nonatomic,retain) UITableView *phontView;
@property (nonatomic,retain) ViewPoint *viewPoint;

@end

static const CGFloat MJDuration = 2.0;

@implementation TravelImpressionController


- (void)MJRefresh
{
    NSLog(@"mjrefresh");
    // 1.下拉刷新
    [self.tableView addLegendHeaderWithRefreshingBlock:^{
        [self loadNewData];
    }];
    
    // 马上进入刷新状态
    [self.tableView.legendHeader beginRefreshing];
    
    //    [self performSelector:@selector(headerRereshing) withObject:self.tableView.tableHeaderView afterDelay:2.0];
    
    
    // 2.上拉加载更多(进入刷新状态就会调用self的footerRereshing)
    //    [self.tableView addFooterWithTarget:self action:@selector(footerRereshing)];
    
    
}




#pragma mark - 数据处理相关
#pragma mark 下拉刷新数据
- (void)loadNewData
{
    // 1.添加假数据
    //    for (int i = 0; i<5; i++) {
    //        [self.data insertObject:MJRandomData atIndex:0];
    //    }
    
    // 2.模拟2秒后刷新表格UI（真实开发中，可以移除这段gcd代码）
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(MJDuration * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        // 刷新表格
        [self.tableView reloadData];
        
        // 拿到当前的下拉刷新控件，结束刷新状态
        [self.tableView.header endRefreshing];
    });
}



-(void)setTitleSegment
{
//    UISegmentedControl *segmentedControl=[[UISegmentedControl alloc] initWithFrame:CGRectMake(80.0f, 8.0f, 100.0f, 30.0f) ];
//    [segmentedControl insertSegmentWithTitle:@"One" atIndex:0 animated:YES];
//    [segmentedControl insertSegmentWithTitle:@"Two" atIndex:1 animated:YES];
//    segmentedControl.momentary = YES;
//    segmentedControl.multipleTouchEnabled=NO;
//    [segmentedControl addTarget:self action:@selector(segmentChangedValue:) forControlEvents:UIControlEventValueChanged];
//    //UIBarButtonItem *segButton = [[UIBarButtonItem alloc] initWithCustomView:segmentedControl];
////    self.seg=segmentedControl;
//    segmentedControl.selectedSegmentIndex=0;
//    [self.navigationItem setTitleView:segmentedControl];
    
    NSInteger margin = 20;
    
    self.switcher = [[DVSwitch alloc] initWithStringsArray:@[@"印象", @"相册"]];
    self.switcher.frame = CGRectMake(margin, margin * 2, self.view.frame.size.width - margin * 8, 28);

    self.switcher.selectedIndex=0;
    [self.switcher setPressedHandler:^(NSUInteger index) {
        
//        NSLog(@"Did press position on first switch at index: %lu", (unsigned long)index);
        UICollectionViewFlowLayout *layout=[[UICollectionViewFlowLayout alloc] init];
        PhotoTVController *photo=[[PhotoTVController alloc] initWithCollectionViewLayout:layout];
        photo.view.backgroundColor=[UIColor redColor];
        photo.viewPoint=_viewPoint;
        photo.view.frame=CGRectMake(0, 64, self.view.frame.size.width, self.view.frame.size.height);
        
        
        if (index==1) {
            self.switcher.selectedIndex=0;
//            NSLog(@"%ld",[self.view.subviews count]);
//            NSLog(@"+++++%@",self.view.subviews);
//            [self.view.subviews[0] removeFromSuperview];
            
//            [self.view.superview insertSubview:photo.view aboveSubview:self.view];
//            if(![self.view.superview.subviews containsObject:photo.view])
//            {
                [self.view.superview addSubview:photo.view];

//            }else
//            {
//                [photo.view bringSubviewToFront:self.view];
//            }
            
      }else{
//          NSLog(@"%ld",[self.view.subviews count]);
//           NSLog(@"------%@",self.view.subviews);
//          [self.view.subviews[0] removeFromSuperview];
//            [self.view bringSubviewToFront:photo.view];
          [self.view.superview addSubview:self.view];
//          NSLog(@"++%ld",[self.view.subviews count]);
        }
        
        
    }];
    [self.navigationItem setTitleView:self.switcher];
}


- (void)setHeaderImage:(UIImageView *)headerImage
{
    _headerImage=[[UIImageView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height*0.3)];
    _headerImage.image=[UIImage imageNamed:@"mood_back"];
}



- (void)segmentChangedValue:(UISegmentedControl*)segment
{
   
    UICollectionViewFlowLayout *layout=[[UICollectionViewFlowLayout alloc] init];
    PhotoTVController *photo=[[PhotoTVController alloc] initWithCollectionViewLayout:layout];
     NSLog(@"before code:%@",self.detail.code);
        photo.code=self.detail.code;
    
    if (segment.selectedSegmentIndex==1) {
        
        [self.navigationController pushViewController:photo animated:YES];
        
    }
    
}


- (void)surroundFood
{
   SurroundingFoodTVController *controller=[[[SurroundingFoodTVController alloc]init] autorelease];
    
    controller.viewPoint=_viewPoint;
   [self.navigationController pushViewController:controller animated:YES];
}

- (void)surroundHouse
{
    SurroundHouseTVController *controller=[[SurroundHouseTVController alloc]init];
    controller.viewPoint=_viewPoint;
    
    [self.navigationController pushViewController:controller animated:YES];
    [self.view removeFromSuperview];
}

- (void)surroundView
{
    SurroundingViewTVController *controller=[[SurroundingViewTVController alloc]init];
    controller.viewPoint=_viewPoint;
    [self.navigationController pushViewController:controller animated:YES];
    [self.view removeFromSuperview];
}


- (void)surroundTraffic
{

    GPSViewController *gps=[[GPSViewController alloc]init];
    
    [self.navigationController pushViewController:gps animated:YES];
    [self.view removeFromSuperview];
    
}



- (void) loadInfo
{
    
//    http://www.roadqu.com/api/mobile/qunawan/poi/detail&a_t=1427875763000&token=55150e044f7c3&code=6e133f9221c36009011e367571778101&sign=68fa74aad0147f2ee78ca1f7074327b3c5793797
    
    
    if (self.detail.code==nil) {
        self.detail.code=@"6e133f9221c36009011e367571778101";
    }
    
    NSString *str=[NSString stringWithFormat:@"http://www.roadqu.com/api/mobile/qunawan/poi/detail&a_t=1427875763000&token=55150e044f7c3&code=%@",self.detail.code];
    
    AFHTTPSessionManager *mgr=[[AFHTTPSessionManager alloc]init];
    [mgr GET:str parameters:nil success:^(NSURLSessionDataTask *task, id responseObject) {
        
            //   NSLog(@"^^^^^^^^^^^^^^^^^^^\n%@",responseObject);
//
        NSDictionary *dic = [responseObject valueForKey:@"data"];
//        NSLog(@"%@",dic);
//        NSLog(@"%@",[dic valueForKey:@"description"]);
        
        
        ViewPoint *v=[[ViewPoint alloc] init];
        v.desp=[dic valueForKey:@"description"];
        v.address=[dic valueForKey:@"address"];
        v.opentime=[dic valueForKey:@"opentime"];
        v.telephone=[dic valueForKey:@"telephone"];
        v.type=[dic valueForKey:@"type"];
        v.name=[dic valueForKey:@"name"];
        v.lat=[[dic valueForKey:@"lat"] intValue];
        v.lng=[[dic valueForKey:@"lng"] intValue];
        v.picArr=[dic valueForKey:@"pic"];
        
//        NSLog(@"=========%@",v.desp);
        self.viewPoint=v;
        
        [self.tableView reloadData];
        
    } failure:nil];
}



- (void)viewDidLoad {
    [super viewDidLoad];
//    self.view.backgroundColor=[UIColor redColor];
    
    [self MJRefresh];
    
    //设置标题栏 segment
    [self setTitleSegment];
    
    [self loadInfo];
    
    NSNotificationCenter *notificationCenter=[NSNotificationCenter defaultCenter];
    
    [notificationCenter addObserver:self selector:@selector(surroundFood) name:@"1" object:nil];
    [notificationCenter addObserver:self selector:@selector(surroundHouse) name:@"2" object:nil];
    [notificationCenter addObserver:self selector:@selector(surroundView) name:@"3" object:nil];
    [notificationCenter addObserver:self selector:@selector(surroundTraffic) name:@"4" object:nil];
    
    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
    
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
    
    
    _headerImage=[[UIImageView alloc] initWithFrame:CGRectZero];
    _headerImage.image=[UIImage imageNamed:@"cover"];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
#warning Potentially incomplete method implementation.
    // Return the number of sections.
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
#warning Incomplete method implementation.
    // Return the number of rows in the section.
    switch (section) {
        case 0:
            return 1;
            break;
            
    }
    return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section==0) {
        return 160;
    }
    return 190;
}


//头部高度
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section==0) {
        return 200;
    }
    return 20;
}


- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if (section==0) {
         return _headerImage;
    }
    return nil;
}


- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    
    switch (section) {
        case 0:
            return @"路友视角";
            break;
            
        case 1:
            return @"指南";
            
        default:
            break;
    }
    return @"";
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *identifier=@"reuse";
    ViewpointTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    SubViewpointTVCell *spcell = [tableView dequeueReusableCellWithIdentifier:identifier];
    switch (indexPath.section) {
        case 0:
            
            if (cell==nil) {
                cell=[[ViewpointTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
            }
            cell.contentLabel.text=self.viewPoint.desp;
            
            //无色
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            
            return cell;
            
            break;
            
    }
    
    if (spcell==nil) {
        spcell=[[SubViewpointTVCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
        
    }
    spcell.viewPoint=self.viewPoint;
//    NSLog(@"-------%@",self.viewPoint.desp);
    // 定义其辅助样式
//    spcell.accessoryType= UITableViewCellAccessoryDisclosureIndicator;
    //无色
    spcell.selectionStyle = UITableViewCellSelectionStyleNone;
    return spcell;
    
}


/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
